package com.ruibang.glass.material.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruibang.glass.material.constant.Constants;
import com.ruibang.glass.material.constant.MaterialErrorCode;
import com.ruibang.glass.material.domain.req.MaterialContentLotReq;
import com.ruibang.glass.material.domain.resp.external.BindInfo;
import com.ruibang.glass.material.domain.resp.external.ContentTypeStartTime;
import com.ruibang.glass.material.domain.resp.external.SalverGlassDataSyncResp;
import com.ruibang.glass.material.domain.resp.external.SyncBcResultResp;
import com.ruibang.glass.material.entity.GlassContainerManager;
import com.ruibang.glass.material.entity.MaterialContent;
import com.ruibang.glass.material.entity.MaterialContentLot;
import com.ruibang.glass.material.entity.MaterialLotItem;
import com.ruibang.glass.material.service.*;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @program: glass
 * @description: 托盘玻璃数据同步接口服务类
 * @author: wujie
 * @create: 2024-02-05 16:02
 */
@Service
public class SalverGlassDataSyncImpl implements SalverGlassDataSync {

    @Autowired
    private GlassContainerManagerService containerManagerService;

    @Autowired
    private MaterialContentLotService materialContentLotService;

    @Autowired
    private MaterialLotItemService materialLotItemService;

    private static final String HOT_GLASS_SY = "SY";//热端玻璃同步

    private static final String COLD_GLASS_SY = "SL"; //冷端玻璃同步

    private static final String SYNC_INIT_TIME = "1668823470334"; //绑定状态数据同步初始时间

    @Override
    public SyncBcResultResp<SalverGlassDataSyncResp> listAShelfDetail(String rackId) {
        SyncBcResultResp resp = new SyncBcResultResp();
        SalverGlassDataSyncResp dataSync = new SalverGlassDataSyncResp();
        GlassContainerManager containerManager = containerManagerService.getByContainerCode(rackId);
        if(containerManager!=null){
            MaterialContentLot contentLot = null;
            if(StringUtils.isNotBlank(containerManager.getBatchNumber())){
                MaterialContentLotReq lotReq = new MaterialContentLotReq();
                lotReq.setContentCode(rackId);
                lotReq.setBatchNumber(containerManager.getBatchNumber());
                contentLot = materialContentLotService.getLotByParams(lotReq);
            }else{
                contentLot = materialContentLotService.getLotByContentCode(rackId);
            }

            if(contentLot==null){
                resp.setState("fail");
                resp.setCode(441);
                resp.setMsg("MOM系统A型架与水平托盘容器["+rackId+"]的未绑定批次");
                return resp;
            }

            String level;
            // TODO 临时处理,待确定level为什么会是0
            if (StringUtils.isBlank(contentLot.getLevel()) || CommonConstant.ZERO_STR.equals(contentLot.getLevel())) {
                level = Optional.ofNullable(contentLot.getResult()).orElse(CommonConstant.ONE_STR);
            } else {
                level = contentLot.getLevel();
            }

            if(StringUtils.isEmpty(level)){
                resp.setState("fail");
                resp.setCode(441);
                resp.setMsg("MOM系统A型架与水平托盘容器level品级异常,id="+contentLot.getLotId());
                return resp;
            }
            String bindId = rackId.concat(CommonConstant.SpecialSign.TRANSVERSE_LINE.getName().concat(contentLot.getBatchNumber()));
            List<MaterialLotItem> lotItems = materialLotItemService.queryGlassBindByParams(bindId);
            int count = materialLotItemService.getCountByBindId(bindId);
            List<BindInfo> bindInfos = lotItems.stream().map(s -> {
                BindInfo bindInfo = new BindInfo();
                bindInfo.set_id(s.getGlassCode());
                bindInfo.setGlass_order_number(s.getGlassSerialNumber());
                bindInfo.setBind_record_id(s.getBindId());
                bindInfo.setBind_status(2);
                bindInfo.setUnbind_time(s.getUnbindTime());
                return bindInfo;
            }).collect(Collectors.toList());

            dataSync.set_id(bindId);
            dataSync.setProduction_line_code(contentLot.getLineName());
            dataSync.setRack_use_batch(contentLot.getBatchNumber());
            dataSync.setRack_id(rackId);
            dataSync.setRack_bind_num(count);
            dataSync.setPz(Integer.parseInt(level));
            dataSync.setList(bindInfos);
        }else{
            resp.setState("fail");
            resp.setCode(441);
            resp.setMsg("未查询到该A型架与水平托盘容器数据");
            return resp;
        }

        resp.setState("ok");
        resp.setCode(200);
        resp.setData(dataSync);
        return resp;
    }

    @Override
    public void sync(String type) {
         if(Constants.TEN_STR.equals(type) || Constants.TWENTY_STR.equals(type)){
            List<ContentTypeStartTime> lotStartTimes = materialContentLotService.getLotTypeStartTime();
            Map<String,String> typeMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(lotStartTimes)){
                typeMap = lotStartTimes.stream().collect(Collectors.toMap(ContentTypeStartTime::getContentType,ContentTypeStartTime::getStartTime,(t1,t2)->t1));
                if(StringUtils.isEmpty(typeMap.get(CommonConstant.TWO_STR))){
                    typeMap.put(CommonConstant.TWO_STR,SYNC_INIT_TIME);
                }
                if(StringUtils.isEmpty(typeMap.get(CommonConstant.THREE_STR))){
                    typeMap.put(CommonConstant.THREE_STR,SYNC_INIT_TIME);
                }
            }else{
                typeMap.put(CommonConstant.TWO_STR,SYNC_INIT_TIME);
                typeMap.put(CommonConstant.THREE_STR,SYNC_INIT_TIME);
            }

            //同步绑定批次数据
            materialContentLotService.syncColdSideLotData(typeMap.get(CommonConstant.TWO_STR));
            materialContentLotService.syncHotSideLotData(typeMap.get(CommonConstant.THREE_STR));
            List<ContentTypeStartTime> itemStartTimes = materialLotItemService.getLotItemTypeStartTime();
            if(CollectionUtils.isNotEmpty(itemStartTimes)){
                typeMap = itemStartTimes.stream().collect(Collectors.toMap(ContentTypeStartTime::getContentType,ContentTypeStartTime::getStartTime,(t1,t2)->t1));
                if(StringUtils.isEmpty(typeMap.get(HOT_GLASS_SY))){
                    typeMap.put(HOT_GLASS_SY,SYNC_INIT_TIME);
                }
                if(StringUtils.isEmpty(typeMap.get(COLD_GLASS_SY))){
                    typeMap.put(COLD_GLASS_SY,SYNC_INIT_TIME);
                }
            }else{
                typeMap.put(HOT_GLASS_SY,SYNC_INIT_TIME);
                typeMap.put(COLD_GLASS_SY,SYNC_INIT_TIME);
            }

            //同步绑定玻璃数据
            materialLotItemService.syncHotSideGLassData(typeMap.get(HOT_GLASS_SY));
            materialLotItemService.syncColdSideGLassData(typeMap.get(COLD_GLASS_SY));

         }
    }



    public static void main(String[] args) {
        Instant instant = Instant.ofEpochMilli(1717718406000L);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(CommonConstant.DATE_TIME_FORMAT);
        String timestr = localDateTime.format(dtf);
        System.out.println(timestr);

        long milliSecondStart = LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.of("+8")).toEpochMilli();

        long milliSecondEnd = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println(milliSecondStart +"   "+milliSecondEnd);
    }
}
